import undetected_chromedriver as uc
import time
import tkinter as tk
import tkinter.filedialog
from lxml import etree
import requests
from concurrent.futures import ThreadPoolExecutor


class get_image():
    def __init__(self):
        self.con = 1
    def get_chromedriver(self):
        window.config(background='yellow')
        self.driver = uc.Chrome(use_subprocess=True)
        self.driver.get('https://lens.google.com/search?p=AU55jv1K1sZxWRRN_W3GUI5iTD1h_5ssKucsVBqgp75YyMh-mpKgZcRdSYQZYKTDUD4LKpDIMh90O899fn6usZINPf2mEK_wj01P5uZ4YgPAFMUXuIKI1EO4CHfg0fvoe-9WzEqXWbJzgnUM192x5w5uNoh1kA3FA6Ya6nsTqiF6trH2YJZ_7lPNDP4qkP-2dgRvtED1sB6Hwcj39CnNqql9zWlztfuIk7xcUSZhcQtlhj_j3VDfwmf35muKKiKPyIcyapP9fwKGOkb39i7hY9uzRUKkQMzSHAcX1yjDl08Ey4Y%3D&ep=gisbubb&hl=zh-CN#lns=W251bGwsbnVsbCxudWxsLG51bGwsbnVsbCxudWxsLG51bGwsIkVrY0tKR1kwTkRreU5XVmxMVGc0WVdNdE5HSmtOeTFoTmpjeUxUaG1ZVGMzWkRsbE0yTm1aQklmT0Y5c1VXZHBjbWx4ZFRSamQwMURZVjlYYUdaVlQxZDFjVVJETWs5NFp3PT0iXQ==')
    def get_images(self):
        window.config(background='yellow')
        html = self.driver.page_source
        etrees = etree.HTML(html)
        img_list = etrees.xpath('//img[@class="wETe9b"]')
        path = tkinter.filedialog.askdirectory(title='选择保存到哪个文件夹：')

        with ThreadPoolExecutor(10) as t:
            for img in img_list:
                a = img.xpath('./@src')[0]
                if 'http' not in a:
                    a = img.xpath('./@data-src')[0]
                t.submit(self.save_images, path=path, url=a , con=self.con)
                self.con+=1
        window.config(background='green')

    def save_images(self, path, url, con):
        data = requests.get(url).content
        with open('{}/{}.jpg'.format(path, str(con).zfill(4)), 'wb') as f:
            f.write(data)







if __name__ == '__main__':
    get_image = get_image()
    # 创建一个主窗口对象
    window = tk.Tk()
    window.config(background='red')
    # 使用按钮控件调用函数
    tk.Button(window, text="点击打浏览器", command=get_image.get_chromedriver).pack()
    tk.Button(window, text="点击下载图片", command=get_image.get_images).pack()
    window.attributes('-topmost',1)
    # 调用mainloop()显示主窗口
    window.mainloop()
